package com.truyen.service.impl;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.googlecode.ehcache.annotations.Cacheable;
import com.truyen.persistence.dao.ChapterTruyenTranhDao;
import com.truyen.persistence.dao.ChapterTmpTruyenTranhDao;
import com.truyen.persistence.entity.ChapterTruyenTranh;
import com.truyen.persistence.entity.ChapterTmpTruyenTranh;
import com.truyen.persistence.entity.LoaiLog;
import com.truyen.persistence.entity.TruyenTranh;
import com.truyen.service.ChapterTruyenTranhService;
import com.truyen.service.ChapterTmpTruyenTranhService;
import com.truyen.service.LoaiLogService;
import com.truyen.service.LogOtherService;
import com.truyen.utils.PagingInfo;


@Service
public class ChapterTruyenTranhServiceImpl implements ChapterTruyenTranhService {
	
	@Autowired
	private ChapterTruyenTranhDao chapterTruyenTranhDao;
	
	@Autowired
	private ChapterTmpTruyenTranhDao chapterTmpTruyenTranhDao;
	
	@Autowired
	private ChapterTmpTruyenTranhService chapterTmpTruyenTranhService;
	
	@Autowired
	private LogOtherService logOtherService;
	
	@Autowired
	private LoaiLogService loaiLogService;

	@Override
	public void save(ChapterTruyenTranh entity) {
		chapterTruyenTranhDao.save(entity);
	}

	// ham cap nhat number cua chapter
	public float getChapterNumber(String nameChapter) {
		LoaiLog loaiLog = loaiLogService.findByProperty("alias", "doi chapter number");
		try {
			// xu ly cat ten truyen den dau :
			int endIndex = nameChapter.lastIndexOf(":");
			if (endIndex == -1) {
				endIndex = nameChapter.length();
			}
			int beginIndex = endIndex - 5;
			if (beginIndex < 0) {
				beginIndex = endIndex - 3;
			}
			String str = nameChapter.substring(beginIndex, endIndex);
			// xu ly cat ten truyen den dau khoang cach sau cung
			endIndex = str.length();
			beginIndex = str.indexOf(" ");
			int khoangTrang = endIndex - beginIndex;
			if (beginIndex > 0 && khoangTrang > 1) {
				str = str.substring(beginIndex, endIndex);
			}
			// xu ly cat ten truyen den dau .
//			endIndex = str.lastIndexOf(".");
//			if (endIndex == -1) {
//				endIndex = str.length();
//			}
//			beginIndex = 0;
//			str = str.substring(beginIndex, endIndex);
//			for (int i = 0; i < length; i++) {
//				Character character = str.charAt(i);
//				if (Character.isDigit(character)) {
//					result += character;
//					chapterNumber = Float.parseFloat(result);
//				}
//			}
			DecimalFormatSymbols symbols = new DecimalFormatSymbols();
			symbols.setDecimalSeparator('.');
			DecimalFormat format = new DecimalFormat("0.#");
			format.setDecimalFormatSymbols(symbols);
			float chapterNumber = format.parse(str.trim()).floatValue();
			return chapterNumber;
		} catch (Exception e) {
			logOtherService.writeLog("ERROR - Cập nhật chaterNumber của chapter truyện ", "Có lỗi xãy ra khi cập nhật chapternumber của chapter truyện "+nameChapter, loaiLog, true);
			return 0;
		}

	}
	
	@Async
	@Transactional
	@Override
	public void updateLstChapterNumberBlogTruyen() {
		LoaiLog loaiLog = loaiLogService.findByProperty("alias", "doi chapter number");
		List<ChapterTmpTruyenTranh> lstAll = chapterTmpTruyenTranhService.getAll();
		int size = lstAll.size();
		for (int i = 0; i < size; i++) {
			ChapterTmpTruyenTranh chapterTmpTruyen = lstAll.get(i);
			ChapterTruyenTranh chapterTruyen = chapterTmpTruyen.getChapterTruyenTranh();
			String nameChapter = chapterTmpTruyen.getName();
			try {
				float newChapterNumber = getChapterNumber(nameChapter);
				if (newChapterNumber > 0) {
					chapterTmpTruyen.setChapterNumber(newChapterNumber);
					chapterTmpTruyenTranhDao.merge(chapterTmpTruyen);
					chapterTruyen.setChapterNumber(newChapterNumber);
					chapterTruyenTranhDao.merge(chapterTruyen);
				}
//				TruyenTranh entity = chapter.getTruyen();
//				List<ChapterTruyenTranh> lstChapterByComic = getAllChapterByComic(truyen);
//				if (lstChapterByComic.size() > 0) {
//					int sizeLst = lstChapterByComic.size();
//					float chapterLastest = 0;
//					for (int ii = 0; ii < sizeLst; ii++) {
//						float currentChapterNumber = lstChapterByComic.get(ii)
//								.getChapterNumber();
//						if (currentChapterNumber > chapterLastest) {
//							chapterLastest = currentChapterNumber;
//						}
//					}
//					truyen.setTotalChapter(chapterLastest);
//					truyenService.save(truyen);
//				}
			}catch (Exception e) {
				logOtherService.writeLog("ERROR - Cập nhật chaterNumber của danh sách chapter truyện", "Có lỗi xãy ra", loaiLog, true);
			}//ket thuc try catch
			logOtherService.writeLog("OK - Cập nhật chaterNumber của danh sách chapter","Đã cập nhật xong "+chapterTmpTruyen.getName(), loaiLog, false);
		}//ket thuc for (int i = 0; i < size; i++) {
	}//ket thuc ham
	
	@Override
	@Cacheable(cacheName="chapterTruyenTranhByIdCacheDataController")
	public ChapterTruyenTranh findById(Long id) {
		return chapterTruyenTranhDao.findById(id);
	}

	@Override
	public List<ChapterTruyenTranh> getAll() {
		return chapterTruyenTranhDao.findAll();
	}

	@Override
	public ChapterTruyenTranh findByProperty(String column, Object value) {
		List<ChapterTruyenTranh> lst = chapterTruyenTranhDao.findByQuery(column, value);
		return (lst.size() > 0)?lst.get(0):null;
	}

	@Override
	public List<ChapterTruyenTranh> getLstChapterByTruyen(TruyenTranh entity,
			String kwSearch, String sort, String sortBy,
			PagingInfo pInfo) {
		return chapterTruyenTranhDao.getLstChapterByTruyen(entity,kwSearch,sort,sortBy,pInfo);
	}

	@Override
	public ChapterTruyenTranh findAliasvTruyen(TruyenTranh entity,	String alias) {
		return chapterTruyenTranhDao.findAliasvTruyen(entity, alias);
	}

	@Override
	public void setIsDelete(Long id) {
		try{
			ChapterTruyenTranh chapter = findById(id);
			boolean isDelete = chapter.getIsDelete();
			if(isDelete){
				chapter.setIsDelete(false);
			}else{
				chapter.setIsDelete(true);
			}
			chapterTruyenTranhDao.merge(chapter);
		}catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	@Cacheable(cacheName="chapterTruyenTranhAllCacheDataController")
	public List<ChapterTruyenTranh> getLstAllChapterTruyen(String kwSearch, String sort, String sortBy, PagingInfo pInfo) {
		return chapterTruyenTranhDao.getLstAllChapterTruyen(kwSearch,sort,sortBy,pInfo);
	}

	@Override
	public void updateChapterNumber(Long id, float chapterNumberChange) {
		try{
			ChapterTruyenTranh chapter = findById(id);
			chapter.setChapterNumber(chapterNumberChange);
			chapterTruyenTranhDao.merge(chapter);
		}catch (Exception e) {
			// TODO: handle exception
		}
		
	}

	@Override
	@Cacheable(cacheName="chapterTruyenTranhCacheTruyenController")
	public List<ChapterTruyenTranh> getByTruyen(TruyenTranh entity) {
		return chapterTruyenTranhDao.getByTruyen(entity);
	}

	@Override
	public ChapterTruyenTranh getChapterByTruyenChapnumber(TruyenTranh entity, float chapterNumber) {
		return chapterTruyenTranhDao.getChapterByTruyenChapnumber(entity,chapterNumber);
	}

	@Override
	@Transactional
	public void delete(long id) {
		try{
			ChapterTruyenTranh chapter = findById(id);
			if(chapter != null){
				chapterTruyenTranhDao.delete(chapter);
			}
		}catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	@Cacheable(cacheName="chapterTruyenTranhMoiCapNhatCacheTruyenController")
	public List<ChapterTruyenTranh> getListNewChapter(int maxLimit) {
		return chapterTruyenTranhDao.getListNewChapter(maxLimit);
	}

	@Override
	public void update(Long id, Float chapterNumber, String content,
			boolean isDelete, boolean isHot) {
		try {
			ChapterTruyenTranh chapter = findById(id);
			if(chapter != null){
				chapter.setChapterNumber(chapterNumber);
				chapter.setContent(content);
				chapter.setIsDelete(isDelete);
				chapter.setIsHot(isHot);
				chapterTruyenTranhDao.merge(chapter);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}

}
